//
//  HYLDrawView.m
//  画板实现
//
//  Created by hyl on 16/6/29.
//  Copyright © 2016年 hyl. All rights reserved.
//

#import "HYLDrawView.h"
#import "HYLDrawPath.h"
@interface HYLDrawView ()
@property (nonatomic,assign) CGPoint curP;
@property (nonatomic,strong) HYLDrawPath *path;
@property (nonatomic,strong) NSMutableArray *pathArrM;
@end

@implementation HYLDrawView



-(void) setImage:(UIImage *)image{
    _image=image;
    [self.pathArrM addObject:image];
    [self setNeedsDisplay];
}


-(NSMutableArray *) pathArrM{
    if (_pathArrM==nil) {
        _pathArrM=[NSMutableArray array];
    }
    return _pathArrM;
}


-(void) awakeFromNib{
    [self setPan];
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        [self setPan];
    }
    return self;
}

-(void) clear{
    [self.pathArrM removeAllObjects];
    [self setNeedsDisplay];
}
-(void) cancel{
    [self.pathArrM removeLastObject];
    [self setNeedsDisplay];
}

#pragma mark - setPan
-(void) setPan{
    UIPanGestureRecognizer *pan= [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:pan];
    self.pathColor=[UIColor blackColor];
    self.lineWidth=1;
}
-(void) pan:(UIPanGestureRecognizer *) pan{
    if (pan.state==UIGestureRecognizerStateBegan) {
        _curP=[pan locationInView:self];
        self.path=[[HYLDrawPath alloc]init];
        [self.path moveToPoint:self.curP];
        self.path.lineWidth=self.lineWidth;
//        [self.pathColor set];
        self.path.pathColor = _pathColor;
        [self.pathArrM addObject:self.path];
    }else if(pan.state==UIGestureRecognizerStateChanged){
        self.curP=[pan locationInView:self];
        [self.path addLineToPoint:self.curP];
        [self setNeedsDisplay];
    }
}

#pragma  mark -drawRect
- (void)drawRect:(CGRect)rect {
    for (HYLDrawPath *path in self.pathArrM) {
        if ([path isKindOfClass:[UIImage class]]) {
            UIImage *image=(UIImage *) path;
//            [image drawAtPoint:CGPointZero];
            [image drawInRect:rect];
        } else {
            
            [path.pathColor set];
            [path stroke];
        }
    }
}


@end
